package com.wzt.lianfirecontrol.fragment.home;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.adapter.BaseRecyclerAdapter;
import com.wzt.lianfirecontrol.adapter.usercenter.UserCenterAdapter;
import com.wzt.lianfirecontrol.adapter.usercenter.UserCenterHeadAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.user.CompanyModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.GildeUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;
import com.xh.common.thread.AsyncExecutor;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class UserCenterFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {
    private BaseActivity activity;
    private View itemContentView;

    private SuperSwipeRefreshLayout swipe_container;
    private RecyclerView rlv_user_center;
    private LinearLayoutManager linearLayoutManager;
    private UserCenterAdapter userCenterAdapter;

    // 头部
    private ImageView iv_user_photo;
    private TextView tv_user_name;
    private LinearLayout ll_user_phone;
    private TextView tv_user_phone;
    private LinearLayout ll_user_center_et;
    private View include_change_company;//切换公司
    private TextView tv_current_company_name;

    private RecyclerView rlv_user_center_head;
    private GridLayoutManager gridLayoutManager;
    private UserCenterHeadAdapter headItemAdapter;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private static final int GET_COMPANY_WHAT = 1;// 获取公司树
    private Dialog changeCompanyDialog;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_user_center, container, false);
            initView();
            initGetCompanyHttpHelper();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipe_container = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipe_container);
        swipe_container.setOnSwipeRefreshListener(this);
        initUserCenterList();
        initUserCenterListHead();

        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        include_progress_bar.setVisibility(View.GONE);
        InitView.instance().initProgressBar(activity, include_progress_bar);

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_no_data.setVisibility(View.GONE);

        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setVisibility(View.GONE);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initUserCenterList() {
        rlv_user_center = itemContentView.findViewById(R.id.rlv_user_center);
        linearLayoutManager = new LinearLayoutManager(activity);
        rlv_user_center.setLayoutManager(linearLayoutManager);
        userCenterAdapter = new UserCenterAdapter(activity);
        rlv_user_center.setAdapter(userCenterAdapter);
        userCenterAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<BannerModel>() {
            @Override
            public void onItemClick(View v, int position, BannerModel data) {
                if ("清理缓存".equals(data.getTitle())){
                    include_progress_bar.setVisibility(View.VISIBLE);
                    Glide.get(activity).clearMemory();
                    AsyncExecutor.execute(new Runnable() {
                        @Override
                        public void run() {
                            Glide.get(activity).clearDiskCache();
                        }
                    });
                    rlv_user_center.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            include_progress_bar.setVisibility(View.GONE);
                        }
                    }, 1500);
                    return;
                }
                activity.setClickAction(data);
            }
        });

        List<BannerModel> bannerModels = new ArrayList<>();
        BannerModel bannerModel = new BannerModel();
        bannerModel.setTitle("我的团队");
        bannerModel.setActionTitle("我的团队");
        bannerModel.setActionType(ConstData.SHOWFRAG);
        bannerModel.setActionValue(ConstData.MYTEAM);
        bannerModel.setImgResource(R.mipmap.icon_user_center_my_team);
        bannerModels.add(bannerModel);
        BannerModel bannerModel1 = new BannerModel();
        bannerModel1.setTitle("联系客服");
        bannerModel1.setActionTitle("联系客服");
        bannerModel1.setActionType(ConstData.SHOWFRAG);
        bannerModel1.setActionValue(ConstData.CONTACTKEFU);
        bannerModel1.setImgResource(R.mipmap.icon_user_center_kefu);
        bannerModels.add(bannerModel1);
        BannerModel bannerModel2 = new BannerModel();
        bannerModel2.setTitle("关于我们");
        bannerModel2.setActionType(ConstData.PAGE_PATH);
        bannerModel2.setActionValue("com.wzt.lianfirecontrol.activity.AboutUsActivity");
        bannerModel2.setImgResource(R.mipmap.icon_user_center_about_us);
        bannerModels.add(bannerModel2);
        BannerModel bannerModel3 = new BannerModel();
        bannerModel3.setTitle("意见反馈");
        bannerModel3.setActionTitle("意见反馈");
        bannerModel3.setActionType(ConstData.SHOWFRAG);
        bannerModel3.setActionValue(ConstData.ADVICEBACK);
        bannerModel3.setImgResource(R.mipmap.icon_user_center_back_fankui);
        bannerModels.add(bannerModel3);
        BannerModel bannerModel4 = new BannerModel();
        bannerModel4.setTitle("清理缓存");
        bannerModel4.setImgResource(R.mipmap.icon_user_center_clear_save);
        bannerModels.add(bannerModel4);
        BannerModel bannerModel5 = new BannerModel();
        bannerModel5.setTitle("设置");
        bannerModel5.setActionTitle("设置");
        bannerModel5.setActionType(ConstData.SHOWFRAG);
        bannerModel5.setActionValue(ConstData.SETTING);
        bannerModel5.setImgResource(R.mipmap.icon_user_center_setting);
        bannerModels.add(bannerModel5);
        userCenterAdapter.addDatas(bannerModels);
    }

    private void initUserCenterListHead() {
        View headView = LayoutInflater.from(activity).inflate(R.layout.head_user_center_list, rlv_user_center, false);
        initListHeadView(headView);
        initUserData();
        userCenterAdapter.setHeaderView(headView);
    }

    private void initUserData() {
        UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
        if (!StringUtils.isEmpty(userInfoModel.getImgUrl())) {
            GildeUtils.loadImageCircle(activity, iv_user_photo, userInfoModel.getImgUrl());
        }else {
            iv_user_photo.setImageResource(R.mipmap.user_icon);
        }
        tv_user_name.setText(userInfoModel.getRealName());
        if (!StringUtils.isEmpty(userInfoModel.getPhone())){
            ll_user_phone.setVisibility(View.VISIBLE);
            tv_user_phone.setText(userInfoModel.getPhone());
        }else {
            ll_user_phone.setVisibility(View.GONE);
        }
    }

    private void initListHeadView(View headView) {
        iv_user_photo = headView.findViewById(R.id.iv_user_photo);
        tv_user_name = headView.findViewById(R.id.tv_user_name);
        ll_user_phone = headView.findViewById(R.id.ll_user_phone);
        tv_user_phone = headView.findViewById(R.id.tv_user_phone);


        ll_user_center_et = headView.findViewById(R.id.ll_user_center_et);
        ll_user_center_et.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BannerModel bannerModel = new BannerModel();
                bannerModel.setActionTitle("个人资料");
                bannerModel.setActionType(ConstData.SHOWFRAG);
                bannerModel.setActionValue(ConstData.CHANGEINFO);
                activity.setClickAction(bannerModel);
            }
        });

        rlv_user_center_head = headView.findViewById(R.id.rlv_user_center_head);
        gridLayoutManager = new GridLayoutManager(activity, 4);
        rlv_user_center_head.setLayoutManager(gridLayoutManager);
        headItemAdapter = new UserCenterHeadAdapter(activity);
        rlv_user_center_head.setAdapter(headItemAdapter);

        List<BannerModel> bannerModels = new ArrayList<>();
        BannerModel bannerModel = new BannerModel();
        bannerModel.setTitle("扫一扫");
        bannerModel.setImgResource(R.mipmap.icon_head_user_sq);
        bannerModel.setActionType(ConstData.SQCODE);
        bannerModels.add(bannerModel);

        BannerModel bannerModel1 = new BannerModel();
        bannerModel1.setTitle("报警\n复核单");
        bannerModel1.setImgResource(R.mipmap.icon_head_user_sq_baojing);
        bannerModel1.setActionType(ConstData.PAGE_PATH);
        bannerModel1.setActionValue("com.wzt.lianfirecontrol.activity.SelectTitleActivity");
        bannerModels.add(bannerModel1);

        BannerModel bannerModel2 = new BannerModel();
        bannerModel2.setTitle("消控室\n值班");
        bannerModel2.setImgResource(R.mipmap.icon_head_user_xiaofang);
        bannerModel2.setActionTitle("消控室值班");
        bannerModel2.setActionType(ConstData.SHOWFRAG);
        bannerModel2.setActionValue(ConstData.DUTYLIST);
        bannerModels.add(bannerModel2);

        BannerModel bannerModel3 = new BannerModel();
        bannerModel3.setTitle("巡检\n检查单");
        bannerModel3.setImgResource(R.mipmap.icon_head_user_xunjian);
        bannerModel3.setActionTitle("巡检巡查");
        bannerModel3.setActionType(ConstData.SHOWFRAG);
        bannerModel3.setActionValue(ConstData.BARFLOOR);
        bannerModels.add(bannerModel3);

        BannerModel bannerModel4 = new BannerModel();
        bannerModel4.setTitle("隐患\n整改单");
        bannerModel4.setImgResource(R.mipmap.icon_head_user_yinhuan);
        bannerModel4.setActionTitle("隐患整改单");
        bannerModel4.setActionType(ConstData.SHOWFRAG);
        bannerModel4.setActionValue(ConstData.BARFLOOR);
        bannerModels.add(bannerModel4);

        BannerModel bannerModel5 = new BannerModel();
        bannerModel5.setTitle("紧急\n维修单");
        bannerModel5.setImgResource(R.mipmap.icon_head_user_jinji);
        bannerModel5.setActionTitle("紧急维修单");
        bannerModel5.setActionType(ConstData.SHOWFRAG);
        bannerModel5.setActionValue(ConstData.BARFLOOR);
        bannerModels.add(bannerModel5);

        BannerModel bannerModel6 = new BannerModel();
        bannerModel6.setTitle("预约\n维保");
        bannerModel6.setImgResource(R.mipmap.icon_head_user_yuyue);
        bannerModel6.setActionTitle("维保预约单");
        bannerModel6.setActionType(ConstData.SHOWFRAG);
        bannerModel6.setActionValue(ConstData.BARFLOOR);
        bannerModels.add(bannerModel6);
        headItemAdapter.addDatas(bannerModels);

        headItemAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<BannerModel>() {
            @Override
            public void onItemClick(View v, int position, BannerModel data) {
                Bundle bundle = new Bundle();
                if (data.getTitle().equals("预约\n维保")){
                    bundle.putString(ConstData.BARTYPE, "2");
                }else if (data.getTitle().equals("紧急\n维修单")){
                    bundle.putString(ConstData.BARTYPE, "4");
                }else if (data.getTitle().equals("隐患\n整改单")){
                    bundle.putString(ConstData.BARTYPE, "5");
                }else if (data.getTitle().equals("巡检\n检查单")){
                    bundle.putString(ConstData.BARTYPE, "6");
                }
                activity.setClickAction(data, bundle);
            }
        });


        // 切换公司
        include_change_company = headView.findViewById(R.id.include_change_company);
        include_change_company.setVisibility(View.GONE);
        ImageView iv_img = include_change_company.findViewById(R.id.iv_img);
        iv_img.setImageResource(R.mipmap.icon_build_count);
        tv_current_company_name = include_change_company.findViewById(R.id.tv_title);
        TextView tv_vice_title = include_change_company.findViewById(R.id.tv_vice_title);
        tv_vice_title.setVisibility(View.GONE);
        TextView tv_user_center_num = include_change_company.findViewById(R.id.tv_user_center_num);
        tv_user_center_num.setVisibility(View.GONE);
    }

    /**
     * 获取公司树
     */
    private void initGetCompanyHttpHelper(){
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        HashMap<String, String> url_params = new HashMap<>();
        UserCenterListHttpHelper getCompanyHttpHelper = new UserCenterListHttpHelper(activity, Url.QUERY_COMPANY_TREE, GET_COMPANY_WHAT, handler, true, url_params);
        getCompanyHttpHelper.setParseJsonData(new UserCenterParseJsonData());
        getCompanyHttpHelper.getHttpRequest();
    }

    private class UserCenterListHttpHelper extends HttpHelper {

        public UserCenterListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class UserCenterParseJsonData extends ParseJsonData {

        public UserCenterParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try {
                switch (what){
                    case GET_COMPANY_WHAT:
                        LinkedList<CompanyModel> companyModels = (LinkedList<CompanyModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr), CompanyModel.class);
                        bundle.putSerializable("companyList", companyModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                }
            }catch (Exception e){
                e.printStackTrace();
                bundle.putBoolean(REQUEST_OK, false);
                bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))) {
            if (msg.what == GET_COMPANY_WHAT){
                include_change_company.setVisibility(View.GONE);
            }
            return;
        }
        switch (msg.what) {
            case GET_COMPANY_WHAT:
                LinkedList<CompanyModel> list = (LinkedList<CompanyModel>) bundle.getSerializable("companyList");
                if (null != list && list.size() > 0){
                    CompanyModel currentCompanyModel = getCurrentCompanyModel(list);
                    if (null == currentCompanyModel){
                        include_change_company.setVisibility(View.GONE);
                    }else {
                        tv_current_company_name.setText(currentCompanyModel.getName());
                        include_change_company.setVisibility(View.VISIBLE);
                        include_change_company.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 切换公司
                                DialogUtils.closeDialog(changeCompanyDialog);
                                changeCompanyDialog = DialogUtils.createChangeCompanyDialog(activity, list);
                                DialogUtils.showDialog(changeCompanyDialog);
                                changeCompanyDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialog) {
                                        updateData();
                                    }
                                });
                            }
                        });
                    }
                }else {
                    include_change_company.setVisibility(View.GONE);
                }
                break;
        }
    }

    /**
     * 获取当前公司
     * @param companyModels
     * @return
     */
    private CompanyModel getCurrentCompanyModel(List<CompanyModel> companyModels){
        String currentCompanyId = UserInfoModel.getCompandId(activity);
        CompanyModel currentCompanyModel = null;
        for (CompanyModel companyModel:companyModels){
            if (currentCompanyId.equals(companyModel.getId())){
                currentCompanyModel = companyModel;
                break;
            }else if (null != companyModel.getChildren() && companyModel.getChildren().size() > 0){
                currentCompanyModel = getCurrentCompanyModel(companyModel.getChildren());
                if (null != currentCompanyModel){
                    break;
                }
            }
        }
        return currentCompanyModel;
    }

    @Override
    public void onSwipeRefresh() {
        swipe_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_container.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    @Override
    public void updateData() {
        super.updateData();
        initGetCompanyHttpHelper();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtils.closeDialog(changeCompanyDialog);
    }

    @Override
    public void skipToTop() {
        super.skipToTop();
        if (null != rlv_user_center && null != userCenterAdapter && userCenterAdapter.getItemCount() > 0){
            rlv_user_center.smoothScrollToPosition(0);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != tv_user_name){
            initUserData();
        }
    }
}
